import {
    createRouter,
    createWebHashHistory
} from 'vue-router'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/pages/Login.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/',
        component: () => import('@/pages/Layout.vue'),
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('@/pages/Home.vue'),
                meta: {
                    title: '主页'
                }
            },
            {
                path: 'about',
                name: 'About',
                component: () => import('@/pages/About.vue'),
                meta: {
                    title: '关于'
                }
            },
            {
                path: 'animation',
                name: 'Animation',
                component: () => import('@/pages/Animation.vue'),
                meta: {
                    title: '动画'
                }
            },
            {
                path: 'chart',
                name: 'Chart',
                component: () => import('@/pages/Chart.vue'),
                meta: {
                    title: '图表'
                }
            },
            {
                path: 'test',
                name: 'Test',
                component: () => import('@/pages/Test.vue'),
                meta: {
                    title: '测试'
                }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    
    let token = getToken()
    if (to.name !== 'Login' && !token) {
        next({ name: 'Login' })
    } else {
        next()
    }
})

router.afterEach((to, from) => {
    NProgress.done()
    document.title = to.meta.title
})

export default router
